package cn.webrx.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
@WebServlet("/upload")
@MultipartConfig
public class Upload extends HttpServlet {
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        //所有表单集合 input type="text" input type="password" input type="file"
        Collection<Part> parts = req.getParts();
        System.out.println(req.getParameter("author"));

        String path = req.getServletContext().getRealPath(String.format("/uploads/%tY%<tm/", System.currentTimeMillis()));
        File file = new File(path);
        if (!file.exists()) file.mkdirs();
        parts.stream().filter(p -> p.getSubmittedFileName() != null).forEach(e -> {
            try {
                String filename = e.getSubmittedFileName();
                String ext = filename.lastIndexOf(".") == -1 ? "" : filename.substring(filename.lastIndexOf("."));
                e.write(String.format("%s/%s%s", file.getAbsolutePath(), UUID.randomUUID(), ext));
            } catch (IOException ex) {

            }
        });

    }
}
